package cn.tedu.charging.cost.dao.repository.impl;

import cn.tedu.chaging.common.utils.JsonUtils;
import cn.tedu.charging.cost.dao.repository.CostRuleCacheRepository;
import cn.tedu.charging.cost.pojo.po.CostRulePO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Repository
public class CostRuleCacheRepositoryImpl implements CostRuleCacheRepository {

    private static final Logger log = LoggerFactory.getLogger(CostRuleCacheRepositoryImpl.class);
    /**
     * redis 常用的数据类型
     * string list hash set zset
     */
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public List<CostRulePO> getCostRuleByStationId(Integer stationId) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String costRuleKey = "COST_RULE_KEY_" + stationId;
        Serializable result = valueOperations.get(costRuleKey);
        if (result != null) {
            log.debug("从redis获取数据:{}",result);
            return getCostRulePOS(result);
        }
        return null;
    }

    /**
     * 将从redis数据库遍历出来的数据转换为List<CostRulePO>
     * @param json
     * @return
     */

    private  List<CostRulePO> getCostRulePOS(Serializable json) {
        List<CostRulePO> costRulePOS = new ArrayList<>();
        List<LinkedHashMap<String,CostRulePO>> mapList = JsonUtils.fromJson(json.toString(), List.class);
        for (LinkedHashMap<String,CostRulePO> map : mapList){
            CostRulePO costRulePO = JsonUtils.convertValue(map, CostRulePO.class);
            costRulePOS.add(costRulePO);
        }
        return costRulePOS;
    }

    @Override
    public void saveCostRule(Integer stationId,List<CostRulePO> costRulePO) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String costRuleKey = "COST_RULE_KEY_" + stationId;
        String json = JsonUtils.toJson(costRulePO);
        valueOperations.set(costRuleKey,json);
    }
}
